package com.dnndo.web.controller.common;

import com.dnndo.common.core.domain.AjaxResult;
import com.dnndo.common.core.domain.R;
import com.dnndo.common.utils.file.FileUploadUtils;
import com.dnndo.common.utils.oss.AliOssUtil;
import com.dnndo.framework.config.ServerConfig;
import com.dnndo.system.domain.vo.UserDictVO;
import com.dnndo.system.service.ISysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private ISysUserService userService;

    /**
     * 获取用户字典值
     */
    @GetMapping("/userDict")
    public R<List<UserDictVO>> userDict() {
        return R.ok(userService.getUserDict());
    }

    /**
     * 上传头像
     */
    @PostMapping("/uploadAvatar")
    @ApiImplicitParam(name = "Authorization", value = "登录标识(token)", required = true, dataType = "String",paramType = "header")
    public R<?> avatarUpload(MultipartFile file) {
        //获取文件名
        String fileName = FileUploadUtils.extractFilename(file);
        //在oss中存储名字
        String objectName = aliOssUtil.getAvatarPath() + fileName;
        try {
            String resultURL = aliOssUtil.upload(file.getBytes(), objectName);
            return R.ok(resultURL, "上传成功");
        } catch (IOException e) {
            return R.fail(500, "上传文件失败");
        }
    }

  /**
   * 上传形象照
   */
  @PostMapping("/uploadimagePhoto")
  @ApiImplicitParam(name = "Authorization", value = "登录标识(token)", required = true, dataType = "String",paramType = "header")
  public R<?> imagePhotoUpload(MultipartFile file) {
    //获取文件名
    String fileName = FileUploadUtils.extractFilename(file);
    //在oss中存储名字
    String objectName = aliOssUtil.getImagePhotoPath() + fileName;
    try {
      String resultURL = aliOssUtil.upload(file.getBytes(), objectName);
      return R.ok(resultURL, "上传成功");
    } catch (IOException e) {
      return R.fail(500, "上传文件失败");
    }
  }

    /**
     * 网络路径上传（单个）返回网络路径
     */
    @ApiImplicitParam(name = "Authorization", value = "登录标识(token)", required = true, dataType = "String",paramType = "header")
    @GetMapping("/uploadOss")
    @ApiOperation(value = "网络路径上传（单个）返回网络路径")
    public R<?> uploadFileOss(String fileUrl) {
        String resultURL = aliOssUtil.upload(fileUrl, aliOssUtil.getUploadPath());
        return R.ok(resultURL,"上传成功");
    }

    /**
     * 文件上传（单个）返回网络路径
     */
    @ApiImplicitParam(name = "Authorization", value = "登录标识(token)", required = true, dataType = "String",paramType = "header")
    @PostMapping("/uploadOss")
    @ApiOperation(value = "文件上传（单个）返回网络路径")
    public R<?> uploadFileOss(MultipartFile file) {
        //获取文件名
        String fileName = FileUploadUtils.extractFilename(file);
        //在oss中存储名字
        String objectName = aliOssUtil.getUploadPath() + fileName;
        try {
            String resultURL = aliOssUtil.upload(file.getBytes(), objectName);
            return R.ok(resultURL,"上传成功");
        } catch (IOException e) {
            return R.fail("上传文件失败");
        }
    }

    /**
     * 文件上传（多个）返回网络路径
     */
    @PostMapping("/uploadImages")
    @ApiImplicitParam(name = "Authorization", value = "登录标识(token)", required = true, dataType = "String",paramType = "header")
    public AjaxResult uploadImages(@RequestParam("files") List<MultipartFile> files) {
        if (files == null || files.isEmpty()) {
            return AjaxResult.error("没有选择要上传的文件");
        }
        try {
            List<String> resultUrls = new ArrayList<>();

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue; // 跳过空文件
                }
                // 获取文件名
                String fileName = FileUploadUtils.extractFilename(file);
                // 在oss中存储路径
                String objectName = aliOssUtil.getUploadPath() + fileName;
                // 上传到OSS
                String resultURL = aliOssUtil.upload(file.getBytes(), objectName);
                if (resultURL != null) {
                    resultUrls.add(resultURL);
                }
            }

            if (resultUrls.isEmpty()) {
                return AjaxResult.error("所有文件上传失败");
            }
            System.out.println(resultUrls);
            return AjaxResult.success("上传成功",resultUrls);
        } catch (IOException e) {
            return AjaxResult.error("上传文件失败: " + e.getMessage());
        }
    }

}
